package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.ArticleReply;
import com.example.forum.model.User;
import com.example.forum.services.IArticleReplyService;
import com.example.forum.services.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @ClassName ArticleReplyController
 * @Description TODO
 * @Author H.
 * @Date 2023/6/20 14:13
 * @Version 1.0
 */
@RestController
@Api(tags = "帖子回复接口")
// 指定测试根路径映射地址前缀
@RequestMapping("/articleReply")
public class ArticleReplyController {

    @Resource
   private IArticleReplyService articleReplyService;
    @Resource
    private IArticleService articleService;

    @ApiOperation("获取帖子回复列表")
    @GetMapping("/getRelies")
    public AppResult<List<ArticleReply>> getRepliesByArticleId(@ApiParam(value = "帖子Id") @RequestParam("articleId") @NonNull Long articleId){
       //获取回复结果
        List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);
        //返回结果
        return AppResult.success(articleReplies);
    }

    @ApiOperation("发表帖子回复")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("帖子Id") @RequestParam("articleId") @NonNull Long articleId,
                           @ApiParam("回复内容") @RequestParam("content") @NonNull String content){
        //校验用户状态
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED.toString());
        }
        if(user.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS.toString());
        }
        //校验帖子状态
        Article article = articleService.selectById(articleId);
        if(article == null || article.getDeleteState() == 1){
            return AppResult.failed("帖子不存在");
        }
        if(article.getState() == 1){
            return  AppResult.failed("已被封贴，不能进行回复");
        }

        //构造回复对象
        ArticleReply articleReply = new ArticleReply();
        articleReply.setArticleId(articleId);
        articleReply.setContent(content);
        articleReply.setPostUserId(user.getId());
        //调用service层
        articleReplyService.create(articleReply);
        //返回结果
        return AppResult.success("回复成功") ;
    }
}
